Array Destructuring
Suppose we have some data that lives in an array, and we want to pluck it out and assign it to a variable.
Traditionally, this has been done by accessing an item by index, and assigning it a value with a typical assignment statement:
const fruits = ['apple', 'banana', 'cantaloupe'];const firstFruit = fruits[0];const secondFruit = fruits[1];
Destructuring assignment offers us a nicer way to accomplish this task:
const fruits = ['apple', 'banana', 'cantaloupe'];const [firstFruit, secondFruit] = fruits;
The first time you see it, those array brackets before the =
look pretty wild.
Here's how I think about it: when the [
]
characters are used after the assignment operator (=
), they're used to package items into an array. When they're used before, they do the opposite, and they unpack items from an array:
// Packing 3 values into an array:const array = [1, 2, 3];
// Unpacking 3 values from an array:const [first, second, third] = array;
Ultimately, this isn't really a game-changer, but it's a neat little party trick that can tidy things up a bit.